$(function () {
    'use strict';

    // 渲染车次信息
    let ticket = $.fn.ticket,
        info = ticket.storage.get('infos'),
        paras = ticket.storage.get('paras'),
        userInfo = ticket.storage.get('userInfo'),
        passengers = ticket.storage.get('passengers'),
        userList;

    $('#dateTime').text(info.startDate.replace('-', '年').replace('-', '月') + '日');
    $('#week').text(info.week);
    $('#start_station').text(paras.from_station_name);
    $('#start_time').text(paras.start_time);
    $('#line').text(paras.station_train_code);
    $('#end_station').text(paras.to_station_name);
    $('#end_time').text(paras.arrive_time);

    // 缓存用户12306信息
    if (userInfo) {
        ticket.doAjax({
            //TODO 用户信息
            url: '/RailwayService/passenger/getKyfwByUser?userId=' + userInfo.userId,
            success: function (resb) {
                if (resb.success) {
                    $('#bound').hide();
                    // ticket.storage.set('passengers', resb.data.passengers);
                    ticket.storage.set('username', resb.data.userName);
                    ticket.storage.set('password', resb.data.passWord);
                }
            }
        });
    }

    // 判断登录状态
    if (ticket.storage.get('login')) {
        $('#bound').hide();
        $('#logged').find('.weui-flex__item').text(ticket.storage.get('username'));
        $('#logged,#modify').removeClass('hide');
        $('#modify').find('.weui-flex__item').addClass('color-orange');

        // 渲染乘车人信息
        userList = ticket.storage.get('userList');
        if (userList) {
            $.each(userList, function (idx) {
                $('#modify').before($('#clone_userInfo').clone().text().replace('乘客姓名', this.passenger_name).replace(
                    '车票类型', this.passenger_type_name + '票').replace('证件号码', this.passenger_id_no).replace(
                    '座位类型', info.seatStyle).replace('车票单价', info.price).replace(/-1/g, idx));
            });
            if (userList.length !== 0) {
                $('.weui-btn-area').removeClass('hide');
            }
        }
    } else {
        if (ticket.storage.get('has_logged')) {
            $.confirm({
                text: '点击确认后重新登录',
                title: '登录超时',
                onOK: function () {
                    ticket.storage.remove(['has_logged']);
                    ticket.login({refresh: true});
                },
                onCancel: function () {
                    ticket.storage.remove(['has_logged']);
                }
            });
        }
    }

    // 12306登录弹窗
    $('#bound,#logged').click(function () {
        $('section').append($("#clone_12306").clone().text());
        setTimeout(function () {
            $('#login').addClass('login-show');
        }, 100);
    });

    $(document)
    // 关闭12306登录弹窗
        .on('click', '.icon-guanbi1', function () {
            $('#login').removeClass('login-show');
            $('.train-mask').fadeOut('fast', function () {
                $('.train-mask,#login').remove();
            });
        })

        // 绑定12306帐号
        .on('click', '#a_login_12306', function () {
            $('.icon-guanbi1').click();
            ticket.storage.set('username', $('#account').val());
            ticket.storage.set('password', $('#pwd').val());
            if (ticket.storage.get('has_logged')) {
                return ticket.login({refresh: true});
            } else {
                return ticket.login();
            }
        })

        // 删除乘车人信息
        .on('click', 'i.icon-jianshao', function () {
            $(this).parents('.userinfo').remove();
            userList.splice(Number($(this).data('idx')), 1);
            ticket.storage.set('userList', userList);
        });

    // 乘车人详情页跳转
    $('#modify').click(function () {
        window.location.href = 'trainPerson.html';
    });

    // 订票
    $('#submit').click(function () {
        let data = $.map(userList, function (obj) {
            obj['seat_type'] = info.seatStyle_code;
            return obj;
        });
        ticket.doAjax({
            url: ticket.url.submit_order,
            data: {traininfo: JSON.stringify(ticket.storage.get('data')[ticket.storage.get('ind')])},
            beforeSend: function () {
                $.showLoading('提交订单中...');
            },
            success: function (resp) {
                switch (Number(resp.error)) {
                    case 0:
                        setTimeout(function () {
                            // 购票
                            ticket.doAjax({
                                url: ticket.url.check_order,
                                data: {passengers: JSON.stringify(data)},
                                beforeSend: function () {
                                    // $.showLoading('订票中......');
                                    $('p.weui-toast_content').text('订票中......');
                                },
                                success: function (resp) {
                                    switch (Number(resp.error)) {
                                        case 0:
                                            ticket.storage.remove(['userList']);
                                            $.alert('购票成功', function () {
                                                window.location.href = 'bookSuccess.html';
                                                $.hideLoading();
                                            });
                                            break;
                                        case 2:
                                        case 3:
                                            ticket.cacheTrain();
                                            $.alert('该用户已在其他地点登录，点击确认后重新登录', function () {
                                                $.hideLoading();
                                                ticket.storage.set('refresh', true);
                                                ticket.login();
                                            });
                                            break;
                                        case 6:
                                        case 7:
                                            ticket.cacheTrain();
                                            $.alert('请求错误', '购票失败', function () {
                                                $.hideLoading();
                                            });
                                            break;
                                        case 11:
                                            ticket.cacheTrain();
                                            $.alert('存在未完成订单，点击确认后跳转至订单页面', '购票失败', function () {
                                                $.hideLoading();
                                                window.location.href = 'trainOrder.html';
                                            });
                                            break;
                                        case 14:
                                            ticket.cacheTrain();
                                            $.alert('该座次以售罄', '购票失败', function () {
                                                $.hideLoading();
                                            });
                                            break;
                                        default:
                                            ticket.cacheTrain();
                                            $.alert('购票失败', function () {
                                                $.hideLoading();
                                            });
                                            break;
                                    }
                                },
                                error: function (xhr) {
                                    ticket.cacheTrain();
                                    $.hideLoading();
                                    $.alert(xhr.statusText);
                                }
                            });
                        }, 2000);
                        break;
                    case 2:
                    case 3:
                        ticket.cacheTrain();
                        $.alert('该用户已在其他地点登录，点击确认后重新登录', function () {
                            $.hideLoading();
                            ticket.login();
                        });
                        break;
                    case 11:
                        ticket.cacheTrain();
                        $.alert('存在未完成订单，点击确认后跳转至订单页面', '购票失败', function () {
                            $.hideLoading();
                            window.location.href = 'trainOrder.html';
                        });
                        break;
                    case 14:
                        ticket.cacheTrain();
                        $.alert('该座次以售罄', '购票失败', function () {
                            $.hideLoading();
                        });
                        break;
                    default:
                        console.log({error: resp});
                        ticket.cacheTrain(); // 重新缓存车次信息
                        $.alert('预定失败', function () {
                            $.hideLoading();
                        });
                        break;
                }
            },
            error: function (xhr) {
                ticket.cacheTrain();
                $.hideLoading();
                console.log(xhr);
                $.alert(xhr.statusText);
            }
        });
    });
});